import FYGlobalVarMgr from "./FYGlobalVarMgr";
import FYBaseUI from "./FYBaseUI";
import FYLog from "./FYLog";
import FYUtility from "./FYUtility";
import FYResMgr from "./FYResMgr";

/** 界面管理器 */
export default class FYUIMgr {
    /** 单例 */
    public static readonly Instance: FYUIMgr = new FYUIMgr();
    private constructor() { }

    /** UI预制字典 */
    private _dictUIPrefab: { [key: string]: cc.Prefab } = {};
    /** UI界面字典 */
    private _dictUIPanel: { [key: string]: FYBaseUI } = {};

    /**
     * 显示界面
     * @param uiName 界面名字
     * @param parent 父对象
     * @param param 参数
     */
    public async show(uiName, parent = FYGlobalVarMgr.Instance.NodeTop, ...param) {
        if (!parent) {
            parent = FYGlobalVarMgr.Instance.NodeTop;
        }

        if (!this._dictUIPrefab[uiName]) {
            this._dictUIPrefab[uiName] = await FYResMgr.Instance.loadPrefabResSync(uiName);
        }

        if (this._dictUIPanel[uiName]) {
            this._dictUIPanel[uiName].setActive(true);
        } else {
            this._dictUIPanel[uiName] = FYUtility.addChildPrefab(parent, this._dictUIPrefab[uiName]).getComponent(FYBaseUI);
        }
        this._dictUIPanel[uiName].node.setSiblingIndex(this._dictUIPanel[uiName].node.parent.childrenCount);
        this._dictUIPanel[uiName].onShow(param);
    }

    /**
     * 隐藏界面
     * @param uiName 界面名字
     */
    public hide(uiName) {
        if (this._dictUIPanel[uiName]) {
            this._dictUIPanel[uiName].setActive(false);
        }
    }

    /**
     * 关闭界面
     * @param uiName 界面名字
     * @param bDestroyPrefab 是否删除预制
     */
    public close(uiName, bDestroyPrefab = false) {
        if (this._dictUIPanel[uiName]) {
            this._dictUIPanel[uiName].node.destroy();
            delete this._dictUIPanel[uiName];
        }

        if (bDestroyPrefab && this._dictUIPrefab[uiName]) {
            this._dictUIPrefab[uiName].destroy();
        }
    }
}
